import Vue from 'vue'
import Vuex from 'vuex'
import { vipsList, getUserInfo,hotelsConfigs,get_config, appInit } from '@/common/api.js';
Vue.use(Vuex) // vue的插件机制
import { FormatDate ,getdiffdate } from "@/util/date.js"

// Vuex.Store 构造器选项
const store = new Vuex.Store({
    // 为了不和页面或组件的data中的造成混淆，state中的变量前面建议加上$符号
    state: {
        // 用户信息
        $userInfo: null,
		$token: '',
		$favList: null,
		$siteConfig: null,
    },
	getters:{
		userInfo: state => state.$userInfo,
		myVipProLevelData(state) {
			if (state.$vips && state.$userInfo && state.$userInfo.vip_pro_level > 0) {
				return state.$vips.filter(e => (e.id - 3) == state.$userInfo.vip_pro_level)[0]
			} else {
				return null
			}
		},
		get_fav(state){
			return function(obj_type, obj_id){
				let favList = state.$favList ? state.$favList : [];
				return favList.findIndex(p => p.obj_type == obj_type && p.obj_id == obj_id) > -1;
			}
		},
		get_favList(state){
			if(state.$favList){
				return state.$favList;
			} else {
				let favList = uni.getStorageSync('$favList');
				return favList ? favList : [];
			}
		}
	},
	actions: {
		getUserinfo(context){
			getUserInfo().then((res)=> {
				context.commit('setUser', res);
			});
		},
		getSiteConfig(context){
			appInit().then((res)=> {
				context.commit('setSiteConfig', res.site);
			});
		}
	},
	mutations:{
		setUser(state, data){
			if(data === null){
				uni.removeStorageSync('$userInfo');
				uni.removeStorageSync('$token');
				state.$userInfo = null;
				state.$token = null;
			} else {
				let $userInfo = {...state.$userInfo}
				Object.keys(data).forEach(key => {
					$userInfo[key] = data[key]
				})
				uni.setStorageSync('$userInfo', $userInfo);
				state.$userInfo = $userInfo;
				if(data.token){
					uni.setStorageSync('$token', data.token);
					state.$token = data.token;	
				}
			}
		},
		setSiteConfig(state, data){
			state.$siteConfig = data;
			uni.setStorageSync('$siteConfig', data);
		},
		fav(state, data){
			let {obj_type, obj_id} = data;
			if(!obj_type || !obj_id){
				return ;
			}
			if(!state.$favList){
				state.$favList = [];
			}
			let index = state.$favList.findIndex(p => p.obj_type == obj_type && p.obj_id == obj_id);
			if(index > -1){
				state.$favList.splice(index, 1);
			} else {
				state.$favList.push(data);
			}
			uni.setStorageSync('$favList', state.$favList);
		},
	},
	
})

export default store
